/* © 2009 ROBO Design
 * http://www.robodesign.ro
 */
var C4;
var mouseX;
var mouseY;
var paint;
var context;
var tempcontext;
var canvasWidth;
var canvasHeight;
var initialMouseX = null;
var initialMouseY = null;
var trajectoryType;
function prepareCanvas()
{
    C4 = $("#dynamicObjectCanvas");
    context = document.getElementById('dynamicObjectCanvas').getContext("2d");
    tempcontext = document.getElementById('highlightObjectCanvas').getContext("2d");

    canvasWidth = jQuery('#dynamicObjectCanvas').width();
    canvasHeight = jQuery("#dynamicObjectCanvas").height();
    $(".ballTrajectoryResponseDiv").html(canvasWidth+","+canvasHeight);
    setUpCanvasEvents();
    setUpToolBar();
    $("#cricketh_fielding_positions").css({ opacity: 0 });
   // $("#cricketh_fielding_positions").hide()
}

function sendBallTrajectoryData()
{


                        sendRequest.setAction('insertBallTrajectory');
            sendRequest.setSendParameters(ballCommentaryDataToPost);
            var hiddenResponseDiv = $('.responseDiv');
            $( "#modalDialogWindow" ).children('#loadingScreen').children().empty();
            hiddenResponseDiv.load(sendRequest.serverURL, sendRequest.getSendData(), function(){
                hiddenResponseDiv.unbind();
                //hiddenResponseDiv.show();
                var insertResponse = (hiddenResponseDiv.html()).replace(/^\s*|\s*$/g,'');
                if (insertResponse == '1')
                {
                    $(".ui-dialog-buttonpane button:contains('Insert Ball Commentary')").unbind();
                    $( "#modalDialogWindow" ).children("#modalWindowContent").fadeOut();

                    loadBallByBallCommentaryWindowContent();
                // getBallStatsIndicator();
                }
                else if (insertResponse == '2')
                {
                    loadFinalResultWindowContent();
                }

                else
                {
                    $(".loadingScreen").hide();
                    $(".ballByBallStatsCommentaryContainer").delay(500).fadeIn('slow');
                    formValidator.updateErrorMessage("Ball Commentary insert has failed. Please contact your software administrator.");
                }


            });
}

function setUpToolBar()
{

    $("#batsmanTypeContainer").hide();
    $('#container_batsmanType').buttonset();
 
    $("input:radio[name=batsmanType]").change(function(){
var batsmanType = $("input:radio[name=batsmanType]:checked").val();
var cricketPitch = $("#cricketh_pitch");
var fieldingPosition = $("#cricketh_fielding_positions");
 var canvasImages = jQuery([]).add(cricketPitch).add(fieldingPosition).add($("#dynamicObjectCanvas"));
if (batsmanType == "Left")
    {
    var rotationLeft = function (){
   canvasImages.rotate({
      angle:0,
      animateTo:180,
        success: function(IMG)
       {

       }
   });
}
rotationLeft();
    }
    else
        {
      var rotationRight = function (){
   canvasImages.rotate({
      angle:180,
      animateTo:0,
        success: function(IMG)
       {

       }
   });
}
rotationRight();
        }
    });

     var batsmanType = $("input:radio[name=batsmanType]:checked");

    $("#highlightCricketPitchAreasButton").change(function(){

        if ($('#highlightCricketPitchAreasButton').is(':checked'))
        {

    $("#batsmanTypeContainer").show('slow');
        var opacityOfCricketFieldPositions = $("#cricketh_fielding_positions").css( 'opacity' );


            $("#cricketh_fielding_positions").animate({
                opacity: 1
            }, 500);
    
        }
        else
        {
            
            $("#cricketh_fielding_positions").animate({
                opacity: 0
            }, 500);
             $("#batsmanTypeContainer").hide('slow');
        }

    });
    
    $("#clearCanvasButton").button({
        icons: {
            primary: "ui-icon-scissors"
        }
    });

$("#highlightCricketPitchAreasButton").button();
setUpToolBarEvents();


}


function setUpToolBarEvents()
{
    $("#clearCanvasButton").click(function(){
        clearCanvas();
    }) ;
         trajectoryType = "line";
    lineTool();
    $("#trajectoryTypeSelector").change(function(){
        C4.unbind();
        clearCanvas();
        var toolType = $("#trajectoryTypeSelector").val();
        switch(toolType)
        {
            case "pencil":
                trajectoryType = "pencil";
                pencilTool();
                break;
            case "line":
                trajectoryType = "line";
                lineTool();
                break;
            case "parabola":
                //Init(true);
                break;
            default:
                lineTool();
                trajectoryType ="line";
                break;
        }
    });
}


var code, point, style, drag = null, dPoint;

// define initial points
function Init(quadratic) {

    point = {
        p1: {
            x:100,
            y:250
        },
        p2: {
            x:400,
            y:250
        }
    };

    if (quadratic) {
        point.cp1 = {
            x: 250,
            y: 100
        };
    }
    else {
        point.cp1 = {
            x: 150,
            y: 100
        };
        point.cp2 = {
            x: 350,
            y: 100
        };
    }

    // default styles
    style = {
        curve:	{
            width: 6,
            color: "#333"
        },
        cpline:	{
            width: 1,
            color: "#C00"
        },
        point: {
            radius: 10,
            width: 2,
            color: "#900",
            fill: "rgba(200,200,200,0.5)",
            arc1: 0,
            arc2: 2 * Math.PI
        }
    }

    // line style defaults
    context.lineCap = "round";
    context.lineJoin = "round";

    // event handlers
    var theCanvas = document.getElementById("dynamicObjectCanvas");
    theCanvas.onmousedown = DragStart;
    theCanvas.onmousemove = Dragging;
    theCanvas.onmouseup = theCanvas.onmouseout = DragEnd;

    DrawCanvas();
}

// draw canvas
function DrawCanvas() {
    context.clearRect(0, 0, 800, 800);

    // control lines
    context.lineWidth = style.cpline.width;
    context.strokeStyle = style.cpline.color;
    context.beginPath();
    context.moveTo(point.p1.x, point.p1.y);
    context.lineTo(point.cp1.x, point.cp1.y);
    if (point.cp2) {
        context.moveTo(point.p2.x, point.p2.y);
        context.lineTo(point.cp2.x, point.cp2.y);
    }
    else {
        context.lineTo(point.p2.x, point.p2.y);
    }
    context.stroke();

    // curve
    context.lineWidth = style.curve.width;
    context.strokeStyle = style.curve.color;
    context.beginPath();
    context.moveTo(point.p1.x, point.p1.y);
    if (point.cp2) {
        context.bezierCurveTo(point.cp1.x, point.cp1.y, point.cp2.x, point.cp2.y, point.p2.x, point.p2.y);
    }
    else {
        context.quadraticCurveTo(point.cp1.x, point.cp1.y, point.p2.x, point.p2.y);
    }
    context.stroke();

    // control points
    for (var p in point) {
        context.lineWidth = style.point.width;
        context.strokeStyle = style.point.color;
        context.fillStyle = style.point.fill;
        context.beginPath();
        context.arc(point[p].x, point[p].y, style.point.radius, style.point.arc1, style.point.arc2, true);
        context.fill();
        context.stroke();
    }

    ShowCode();
}


// show canvas code
function ShowCode() {
//		if (code) {
//			code.firstChild.nodeValue =
//				"canvas = document.getElementById(\"canvas\");\n"+
//				"ctx = canvas.getContext(\"2d\")\n"+
//				"ctx.lineWidth = " + style.curve.width +
//				";\nctx.strokeStyle = \"" + style.curve.color +
//				"\";\nctx.beginPath();\n" +
//				"ctx.moveTo(" + point.p1.x + ", " + point.p1.y +");\n" +
//				(point.cp2 ?
//					"ctx.bezierCurveTo("+point.cp1.x+", "+point.cp1.y+", "+point.cp2.x+", "+point.cp2.y+", "+point.p2.x+", "+point.p2.y+");" :
//					"ctx.quadraticCurveTo("+point.cp1.x+", "+point.cp1.y+", "+point.p2.x+", "+point.p2.y+");"
//				) +
//				"\nctx.stroke();"
//			;
//		}
}


// start dragging
function DragStart(e) {
    e = MousePos(e);
    var dx, dy;
    for (var p in point) {
        dx = point[p].x - e.x;
        dy = point[p].y - e.y;
        var theCanvas = document.getElementById("dynamicObjectCanvas");
        //if ((dx * dx) + (dy * dy) < style.point.radius * style.point.radius) {
        drag = p;
        dPoint = e;
        theCanvas.style.cursor = "move";
        return;
    //}
    }
}


// dragging
function Dragging(e) {
    if (drag) {
        e = MousePos(e);
        point[drag].x += e.x - dPoint.x;
        point[drag].y += e.y - dPoint.y;
        dPoint = e;
        DrawCanvas();
    }
}


// end dragging
function DragEnd(e) {
    drag = null;
    var theCanvas = document.getElementById("dynamicObjectCanvas");
    theCanvas.style.cursor = "default";
    DrawCanvas();
}


// event parser
function MousePos(event) {
    var a;
    var b;
    $(document).mousemove(function(e){
        a = e.pageX ;
        b = e.pageY;

    });
    var canvasPosition = $("#gameViewer").position();
    var modalWindowPosition = $(".ui-dialog").position();
    //  initialMouseX = e.pageX - canvasPosition.left - modalWindowPosition.left -20;
    //  initialMouseY = e.pageY - canvasPosition.top - modalWindowPosition.top -40;
    var theCanvas = document.getElementById("dynamicObjectCanvas");
    return {
        x: a - canvasPosition.left - modalWindowPosition.left -20,
        y: b - canvasPosition.top - modalWindowPosition.top -40
    }
}






function lineTool()
{
    // The line tool.

    C4.mousedown(function(e){
        clearCanvas();
        var canvasPosition = $("#gameViewer").position();
        var modalWindowPosition = $(".ui-dialog").position();
        initialMouseX = e.pageX - canvasPosition.left - modalWindowPosition.left -20;
        initialMouseY = e.pageY - canvasPosition.top - modalWindowPosition.top -40;
        addClick(initialMouseX, initialMouseY);
        paint = true;
    });

    C4.mousemove(function(e){
        if(paint){
            var canvasPosition = $("#gameViewer").position();
            var modalWindowPosition = $(".ui-dialog").position();
            mouseX = e.pageX - canvasPosition.left - modalWindowPosition.left -20;
            mouseY = e.pageY - canvasPosition.top - modalWindowPosition.top -40;

            $(".ballTrajectoryResponseDiv").html(mouseX+","+mouseY);
            tempcontext.clearRect(0, 0, 800, 800);
            tempcontext.strokeStyle = "#ffcf33";
            tempcontext.lineJoin = "round";
            tempcontext.lineWidth = 5;
            tempcontext.beginPath();
            tempcontext.moveTo(initialMouseX, initialMouseY);
            tempcontext.lineTo(mouseX,  mouseY);
            tempcontext.stroke();
            tempcontext.closePath();
        }
    });

    C4.mouseup(function(e){
        addClick(mouseX, mouseY);
        if (paint)
        {
            paint = false;
            img_update();
        }

    });
}

// This function draws the #imageTemp canvas on top of #imageView, after which
// #imageTemp is cleared. This function is called each time when the user
// completes a drawing operation.
function img_update () {
    //var canvas = $("#highlightObjectCanvas");
    var thetempCanvas = document.getElementById("highlightObjectCanvas");
    context.drawImage(thetempCanvas, 0, 0);
    tempcontext.clearRect(0, 0, 800, 800);
}
function pencilTool()
{
    clickX = [];
    clickY = [];
    clickDrag = [];
    C4.mousedown(function(e){
        var canvasPosition = $("#gameViewer").position();
        var modalWindowPosition = $(".ui-dialog").position();
        mouseX = e.pageX - canvasPosition.left - modalWindowPosition.left -20;
        mouseY = e.pageY - canvasPosition.top - modalWindowPosition.top -40;
        // var position = $( "#modalDialogWindow" ).dialog( "option", "position" );
        $(".ballTrajectoryResponseDiv").html(mouseX+","+mouseY);
        paint = true;
        addClick(mouseX, mouseY);
        redraw();
    });

    C4.mousemove(function(e){
        if(paint){
            var canvasPosition = $("#gameViewer").position();
            var modalWindowPosition = $(".ui-dialog").position();
            mouseX = e.pageX - canvasPosition.left - modalWindowPosition.left -20;
            mouseY = e.pageY - canvasPosition.top - modalWindowPosition.top -40;

            // var mouseX = e.pageX - canvasPosition.left;
            //    var position = $( "#modalDialogWindow" ).dialog( "option", "position" );
            //  var mouseY = e.pageY - canvasPosition.top;
            $(".ballTrajectoryResponseDiv").html(mouseX+","+mouseY);
            addClick(mouseX, mouseY, true);
            redraw();
        }
    });

    C4.mouseup(function(e){
        paint = false;
    });


    C4.mouseleave(function(e){
        paint = false;
    });
}

function setUpCanvasEvents()
{



}


var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;

function addClick(x, y, dragging)
{
    clickX.push(x);
    clickY.push(y);
    clickDrag.push(dragging);
}

/**
* Clears the canvas.
*/
function clearCanvas()
{
    context.fillStyle = '#ffffff'; // Work around for Chrome
    //   context.clearRect ( x , y , w , h );
    clickX = [];
    clickY = [];
    clickDrag = [];
    context.clearRect(0, 0, 800, 800); // Fill in the canvas with white
    context.width = context.width; // clears the canvas
}


function redraw(){
    C4.width = C4.width; // Clears the canvas

    context.strokeStyle = "#ffcf33";
    context.lineJoin = "round";
    context.lineWidth = 5;

    for(var i=0; i < clickX.length; i++)
    {
        context.beginPath();
        if(clickDrag[i] && i){
            context.moveTo(clickX[i-1], clickY[i-1]);
        }else{
            context.moveTo(clickX[i]-1, clickY[i]);
        }
        context.lineTo(clickX[i], clickY[i]);
        context.closePath();
        context.stroke();
    }
}












/*
 * Canvas curves example
 *
 * By Craig Buckler,		http://twitter.com/craigbuckler
 * of OptimalWorks.net		http://optimalworks.net/
 * for SitePoint.com		http://sitepoint.com/
 *
 * Refer to:
 * http://blogs.sitepoint.com/html5-canvas-draw-quadratic-curves/
 * http://blogs.sitepoint.com/html5-canvas-draw-bezier-curves/
 *
 * This code can be used without restriction.
 */

//(function() {
//
//	var canvas, ctx, code, point, style, drag = null, dPoint;
//
//	// define initial points
//	function Init(quadratic) {
//
//		point = {
//			p1: { x:100, y:250 },
//			p2: { x:400, y:250 }
//		};
//
//		if (quadratic) {
//			point.cp1 = { x: 250, y: 100 };
//		}
//		else {
//			point.cp1 = { x: 150, y: 100 };
//			point.cp2 = { x: 350, y: 100 };
//		}
//
//		// default styles
//		style = {
//			curve:	{ width: 6, color: "#333" },
//			cpline:	{ width: 1, color: "#C00" },
//			point: { radius: 10, width: 2, color: "#900", fill: "rgba(200,200,200,0.5)", arc1: 0, arc2: 2 * Math.PI }
//		}
//
//		// line style defaults
//		ctx.lineCap = "round";
//		ctx.lineJoin = "round";
//
//		// event handlers
//		canvas.onmousedown = DragStart;
//		canvas.onmousemove = Dragging;
//		canvas.onmouseup = canvas.onmouseout = DragEnd;
//
//		DrawCanvas();
//	}
//
//
//
//
//
//	// start
//	canvas = document.getElementById("canvas");
//	code = document.getElementById("code");
//	if (canvas.getContext) {
//		ctx = canvas.getContext("2d");
//		Init(canvas.className == "quadratic");
//	}
//
//})();






// Keep everything in anonymous function, called on window load.
//function setUPCanvas()
//{
//
//
//
//
//
//
///* © 2009 ROBO Design
// * http://www.robodesign.ro
// */
//
//// Keep everything in anonymous function, called on window load.
//if(window.addEventListener) {
//window.addEventListener('load', function () {
//  var canvas, context, canvaso, contexto;
//
//  // The active tool instance.
//  var tool;
//  var tool_default = 'line';
//
//  function init () {
//    // Find the canvas element.
//    canvaso = document.getElementById('imageView');
//    if (!canvaso) {
//      alert('Error: I cannot find the canvas element!');
//      return;
//    }
//
//    if (!canvaso.getContext) {
//      alert('Error: no canvas.getContext!');
//      return;
//    }
//
//    // Get the 2D canvas context.
//    contexto = canvaso.getContext('2d');
//    if (!contexto) {
//      alert('Error: failed to getContext!');
//      return;
//    }
//
//    // Add the temporary canvas.
//    var container = canvaso.parentNode;
//    canvas = document.createElement('canvas');
//    if (!canvas) {
//      alert('Error: I cannot create a new canvas element!');
//      return;
//    }
//
//    canvas.id     = 'imageTemp';
//    canvas.width  = canvaso.width;
//    canvas.height = canvaso.height;
//    container.appendChild(canvas);
//
//    context = canvas.getContext('2d');
//
//    // Get the tool select input.
//    var tool_select = document.getElementById('dtool');
//    if (!tool_select) {
//      alert('Error: failed to get the dtool element!');
//      return;
//    }
//    tool_select.addEventListener('change', ev_tool_change, false);
//
//    // Activate the default tool.
//    if (tools[tool_default]) {
//      tool = new tools[tool_default]();
//      tool_select.value = tool_default;
//    }
//
//    // Attach the mousedown, mousemove and mouseup event listeners.
//    canvas.addEventListener('mousedown', ev_canvas, false);
//    canvas.addEventListener('mousemove', ev_canvas, false);
//    canvas.addEventListener('mouseup',   ev_canvas, false);
//  }
//
//  // The general-purpose event handler. This function just determines the mouse
//  // position relative to the canvas element.
//  function ev_canvas (ev) {
//    if (ev.layerX || ev.layerX == 0) { // Firefox
//      ev._x = ev.layerX;
//      ev._y = ev.layerY;
//    } else if (ev.offsetX || ev.offsetX == 0) { // Opera
//      ev._x = ev.offsetX;
//      ev._y = ev.offsetY;
//    }
//
//    // Call the event handler of the tool.
//    var func = tool[ev.type];
//    if (func) {
//      func(ev);
//    }
//  }
//
//  // The event handler for any changes made to the tool selector.
//  function ev_tool_change (ev) {
//    if (tools[this.value]) {
//      tool = new tools[this.value]();
//    }
//  }
//
//  // This function draws the #imageTemp canvas on top of #imageView, after which
//  // #imageTemp is cleared. This function is called each time when the user
//  // completes a drawing operation.
//  function img_update () {
//		contexto.drawImage(canvas, 0, 0);
//		context.clearRect(0, 0, canvas.width, canvas.height);
//  }
//
//  // This object holds the implementation of each drawing tool.
//  var tools = {};
//
//  // The drawing pencil.
//  tools.pencil = function () {
//    var tool = this;
//    this.started = false;
//
//    // This is called when you start holding down the mouse button.
//    // This starts the pencil drawing.
//    this.mousedown = function (ev) {
//        context.beginPath();
//        context.moveTo(ev._x, ev._y);
//        tool.started = true;
//    };
//
//    // This function is called every time you move the mouse. Obviously, it only
//    // draws if the tool.started state is set to true (when you are holding down
//    // the mouse button).
//    this.mousemove = function (ev) {
//      if (tool.started) {
//        context.lineTo(ev._x, ev._y);
//        context.stroke();
//      }
//    };
//
//    // This is called when you release the mouse button.
//    this.mouseup = function (ev) {
//      if (tool.started) {
//        tool.mousemove(ev);
//        tool.started = false;
//        img_update();
//      }
//    };
//  };
//
//  // The rectangle tool.
//  tools.rect = function () {
//    var tool = this;
//    this.started = false;
//
//    this.mousedown = function (ev) {
//      tool.started = true;
//      tool.x0 = ev._x;
//      tool.y0 = ev._y;
//    };
//
//    this.mousemove = function (ev) {
//      if (!tool.started) {
//        return;
//      }
//
//      var x = Math.min(ev._x,  tool.x0),
//          y = Math.min(ev._y,  tool.y0),
//          w = Math.abs(ev._x - tool.x0),
//          h = Math.abs(ev._y - tool.y0);
//
//      context.clearRect(0, 0, canvas.width, canvas.height);
//
//      if (!w || !h) {
//        return;
//      }
//
//      context.strokeRect(x, y, w, h);
//    };
//
//    this.mouseup = function (ev) {
//      if (tool.started) {
//        tool.mousemove(ev);
//        tool.started = false;
//        img_update();
//      }
//    };
//  };
//context = document.getElementById('canvasInAPerfectWorld').getContext("2d");
//  // The line tool.
//  tools.line = function () {
//    var tool = this;
//    this.started = false;
//
//    this.mousedown = function (ev) {
//      tool.started = true;
//      tool.x0 = ev._x;
//      tool.y0 = ev._y;
//    };
//
//    this.mousemove = function (ev) {
//      if (!tool.started) {
//        return;
//      }
//
//      context.clearRect(0, 0, canvas.width, canvas.height);
//
//      context.beginPath();
//      context.moveTo(tool.x0, tool.y0);
//      context.lineTo(ev._x,   ev._y);
//      context.stroke();
//      context.closePath();
//    };
//
//    this.mouseup = function (ev) {
//      if (tool.started) {
//        tool.mousemove(ev);
//        tool.started = false;
//        img_update();
//      }
//    };
//  };
//
//  init();
//
//}, false); }
//
//
//}

// vim:set spell spl=en fo=wan1croql tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:

